package com.juntu.loginlib;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.juntu.loginlib.contact.AppConfigContact;
import com.juntu.loginlib.contact.LoginOutContact;
import com.juntu.loginlib.contact.LoginResultContact;
import com.juntu.loginlib.contact.LoginUrl;
import com.juntu.loginlib.entity.LoginInfo;
import com.juntu.loginlib.ex.LoginException;
import com.juntu.loginlib.net.NetClient;
import com.juntu.loginlib.util.LoginUtil;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by cj on 2021/2/18.
 * Email:codesexy@163.com
 * Function:
 * desc:登录中心
 */
public class LoginCenter {

    private LoginCenter() {
        gson = new Gson();
    }

    private static LoginCenter mInstance;
    private Gson gson;


    public static LoginCenter getInstance() {
        if (mInstance == null) {
            synchronized (LoginCenter.class) {
                if (mInstance == null) {
                    mInstance = new LoginCenter();
                }
            }
        }
        return mInstance;
    }


    public void doLogin(@NonNull final LoginInfo info,
                        @Nullable final LoginResultContact contact) {

        String loginUrl = LoginUrl.getLoginUrl();

        String userName = info.getUserName();
        String psw = info.getPsw();
        String placeId = info.getPlaceId();
        String loginType = info.getLoginType();

        HttpUrl.Builder httpUrlBuild = HttpUrl.parse(loginUrl).newBuilder();
        HttpUrl url = httpUrlBuild.addQueryParameter("password", psw)
                .addQueryParameter("username", userName)
                .addQueryParameter("dlzdlx", loginType)
                .addQueryParameter("dlcslx", placeId)
                .addQueryParameter("sbbh", LoginUtil.getDeviceId())
                .build();

        Request request = new Request.Builder().url(url).build();
        Call call = NetClient.getInstance().getRequestCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                if (!call.isCanceled()) call.cancel();
                contact.onError(new LoginException("登录失败"));
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!call.isCanceled()) call.cancel();
                if (response.isSuccessful()) {
                    String body = response.body().string();
                    try {
                        JSONObject json = new JSONObject(body);
                        int code = json.getInt("code");
                        if (code == 1002) {//注册设备
                            try {
                                Boolean isSuccess = registerDevice();
                                if (isSuccess) {
                                    //注册成功之后继续登录
                                    doLogin(info, contact);
                                } else {
                                    contact.onError(new LoginException("注册设备出错"));
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                                contact.onError(new LoginException("注册设备出错"));
                            }
                        } else if (code == 200) {//登录成功
                            contact.onSuccess(body);
                        } else if (code == 1001) {
                            contact.onError(new LoginException("帐号密码错误"));
                        } else {
                            contact.onError(new LoginException("登录失败"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        contact.onError(new LoginException("注册设备出错"));
                    }

                } else {
                    contact.onError(new LoginException("登录失败"));
                }
            }
        });


    }


    public void getAppConfig(@NonNull final String configType, boolean needDialog, @NonNull final AppConfigContact contact) {
        String url = LoginUrl.getAppConfigUrl();
        HttpUrl.Builder httpUrlBuild = HttpUrl.parse(url).newBuilder();
        if (!TextUtils.isEmpty(configType)) {
            httpUrlBuild.addQueryParameter("configType", configType);
        }

        HttpUrl httpUrl = httpUrlBuild.build();
        Request request = new Request.Builder().url(httpUrl)
                .build();

        Call call = NetClient.getInstance().getRequestCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                if (!call.isCanceled()) call.cancel();
                contact.getConfigError(new LoginException("获取配置信息失败了"));
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!call.isCanceled()) call.cancel();
                if (response.isSuccessful()) {
                    String data = response.body().string();
                    if (TextUtils.isEmpty(data)) {
                        contact.getConfigError(new LoginException("获取配置信息失败了"));
                    } else {
                        contact.getConfigSuccess(data);
                    }
                } else {
                    contact.getConfigError(new LoginException("获取配置信息失败了"));
                }
            }
        });
    }

    public void getAppConfig(@NonNull final String configType, @NonNull final AppConfigContact contact) {
        getAppConfig(configType, true, contact);
    }


    public void loginOut(String token, @NonNull final LoginOutContact contact) {
        String url = LoginUrl.getLoginOutUrl();
        HttpUrl.Builder httpUrlBuild = HttpUrl.parse(url).newBuilder();

        HttpUrl httpUrl = httpUrlBuild.build();
        Request request = new Request.Builder()
                .header("XFAuth", token)
                .url(httpUrl)
                .build();

        Call call = NetClient.getInstance().getRequestCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                if (!call.isCanceled()) call.cancel();
                contact.onError(new LoginException("退出登录出错"));
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!call.isCanceled()) call.cancel();
                if (response.isSuccessful()) {
                    String data = response.body().string();
                    try {
                        JSONObject json = new JSONObject(data);
                        int code = json.getInt("code");
                        if (code == 200) contact.onSuccess();
                        else contact.onError(new LoginException("退出登录出错"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                        contact.onError(new LoginException("退出登录出错,解析出错"));
                    }
                } else {
                    contact.onError(new LoginException("退出登录出错,解析出错"));
                }
            }
        });
    }


    /**
     * 注册设备信息
     *
     * @return
     * @throws IOException
     */
    private Boolean registerDevice() throws IOException {
        JsonObject json = new JsonObject();
        json.addProperty("sbbh", LoginUtil.getDeviceId());
        json.addProperty("pp", LoginUtil.getDeviceManufacturer());
        json.addProperty("xh", LoginUtil.getSystemDevice());
        String data = gson.toJson(json);

        HttpUrl.Builder httpUrlBuild = HttpUrl.parse(LoginUrl.getDeviceRegisterUrl()).newBuilder();
        HttpUrl url = httpUrlBuild.addQueryParameter("data", data).build();

        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = NetClient.getInstance().getRequestCall(request);
        Response response = call.execute();
        return response.isSuccessful();
    }


}
